package com.example.jdbcdemo.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity webSecurity)throws Exception{
        webSecurity.ignoring().antMatchers("/**");
    }
    //登录拦截器和权限管理
    //Security如何适合前后端分离？
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 定制请求的授权规则
        // 首页所有人可以访问
        httpSecurity.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1");//level1只有vip1可以访问
        // 开启自动配置的登录功能,访问未经授权的页面会跳到Security自带的Login界面
        // "/login" 请求来到登录页
        // "/login?error" 重定向到这里表示登录失败
        //登录通过后到达index.html页面
        //httpSecurity.formLogin();
    }


    @Autowired
    private DataSource dataSource;

    //认证
    //passwordEncoder给密码加密更安全
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据正常应该从数据库中取，现在从内存中取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin0").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");

    }
}
